package com.zzh.zzhaiagent.utils;

import com.zzh.zzhaiagent.domain.entity.UserProfiles;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT工具类
 */
public class JwtUtil {

    //有效期为
    public static final Long JWT_TTL = 60 * 60 *1000L;// 60 * 60 *1000  一个小时

    public static final Long JWT_TTL_REFRESH = 60 * 60 *1000L * 24 * 7;// 60 * 60 *1000  7天

    //设置秘钥明文
    //你定义的JWT_KEY值是"ai-agent-love-manus-zzh"，其中的连字符-并非 Base64 编码字符 !!! 换一个Key
    public static final String JWT_KEY = "aiAgentLoveManusZzh";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成加密后的秘钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 生成jtw
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间
        return builder.compact();
    }

    /**
     * 创建token
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if(ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)              //唯一的ID
                .setSubject(subject)   // 主题  可以是JSON数据
                .setIssuer("zzh")     // 签发者
                .setIssuedAt(now)      // 签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥
                .setExpiration(expDate);
    }

    /**
     * 解析
     * @param jwt jwt
     * @return Claims 返回标识信息，如果null则异常
     */
    public static Claims parseJWT(String jwt){
        try {
            SecretKey secretKey = generalKey();
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 判断是否token过期
     */
    public static boolean isTokenExpired(String token){
        try {
            return parseJWT(token).getExpiration().before(new Date());
        }catch (Exception e){//如果捕获到异常，说明token已经过期了
            return false;
        }
    }

    /**
     * 生成refreshToken
     * @param subject token中要存放的数据 主题数据
     * @return refreshToken
     */
    public static String createRefreshToken(String subject){
        return createJWT(subject, JWT_TTL_REFRESH);
    }

    /**
     * refresh 刷新token
     * @param accessToken 旧token
     * @param refreshToken 刷新token
     * @return 新token
     */
    public static String refreshToken(String accessToken,String refreshToken){
        boolean isTokenExpired = isTokenExpired(accessToken);
        if(!isTokenExpired){
            return accessToken;
        }
        Claims claims = parseJWT(refreshToken);//获取到token的唯一标识
        String subject = claims.getSubject();
        return createJWT(subject);
    }



    public static void main(String[] args) throws Exception {
        String jwt = createJWT("2123");
        System.out.println(jwt);
        Claims claims = parseJWT(jwt);
        String subject = claims.getSubject();
        System.out.println(subject);
    }


}